package com.markerhub.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.markerhub.entity.SysOperationLog;
import com.markerhub.mapper.SysOperationLogMapper;
import com.markerhub.service.SysOperationLogService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统操作日志服务实现类
 */
@Service
public class SysOperationLogServiceImpl extends ServiceImpl<SysOperationLogMapper, SysOperationLog> implements SysOperationLogService {

    @Override
    public Map<String, Object> analysis(Date startTime, Date endTime, String type) {
        // 构建查询条件
        QueryWrapper<SysOperationLog> queryWrapper = new QueryWrapper<>();
        
        // 按时间范围查询
        if (startTime != null) {
            queryWrapper.ge("created", startTime);
        }
        if (endTime != null) {
            queryWrapper.le("created", endTime);
        }
        
        // 获取符合条件的所有操作日志
        List<SysOperationLog> logs = this.list(queryWrapper);
        
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        long totalCount = logs.size();
        
        if (totalCount > 0) {
            switch (type) {
                case "module":
                    // 按模块分析
                    Map<String, Long> moduleCount = logs.stream()
                            .collect(Collectors.groupingBy(log -> {
                                // 简化处理，从method中提取模块信息
                                String method = log.getMethod();
                                if (method != null && method.contains("/")) {
                                    String[] parts = method.split("/");
                                    if (parts.length > 3) {
                                        return parts[2];
                                    }
                                }
                                return "其他";
                            }, Collectors.counting()));
                    
                    // 转换为前端需要的格式
                    for (Map.Entry<String, Long> entry : moduleCount.entrySet()) {
                        Map<String, Object> item = new HashMap<>();
                        item.put("name", entry.getKey());
                        item.put("count", entry.getValue());
                        item.put("percentage", Math.round((entry.getValue() * 100.0 / totalCount) * 100) / 100.0);
                        list.add(item);
                    }
                    break;
                    
                case "operation":
                    // 按操作类型分析
                    Map<String, List<SysOperationLog>> operationLogs = logs.stream()
                            .collect(Collectors.groupingBy(SysOperationLog::getOperation));
                    
                    // 计算每个操作的统计信息
                    for (Map.Entry<String, List<SysOperationLog>> entry : operationLogs.entrySet()) {
                        List<SysOperationLog> operationList = entry.getValue();
                        long count = operationList.size();
                        double avgTime = operationList.stream()
                                .mapToLong(SysOperationLog::getTime)
                                .average()
                                .orElse(0);
                        double successRate = operationList.stream()
                                .filter(log -> log.getStatus() == 1)
                                .count() * 1.0 / count;
                        
                        Map<String, Object> item = new HashMap<>();
                        item.put("name", entry.getKey());
                        item.put("count", count);
                        item.put("percentage", Math.round((count * 100.0 / totalCount) * 100) / 100.0);
                        item.put("avgTime", Math.round(avgTime * 100) / 100.0);
                        item.put("successRate", Math.round(successRate * 10000) / 10000.0);
                        list.add(item);
                    }
                    break;
                    
                case "time":
                    // 按时间分布分析（简化为按小时）
                    Map<Integer, Long> hourCount = logs.stream()
                            .collect(Collectors.groupingBy(log -> {
                                Calendar cal = Calendar.getInstance();
                                // 确保有正确的Date类型参数
                                Object created = log.getCreated();
                                if (created instanceof java.time.LocalDateTime) {
                                    // 如果是LocalDateTime类型，转换为Date
                                    java.time.LocalDateTime localDateTime = (java.time.LocalDateTime) created;
                                    java.time.ZonedDateTime zonedDateTime = localDateTime.atZone(java.time.ZoneId.systemDefault());
                                    java.util.Date date = java.util.Date.from(zonedDateTime.toInstant());
                                    cal.setTime(date);
                                } else if (created instanceof java.util.Date) {
                                    // 如果已经是Date类型，直接使用
                                    cal.setTime((java.util.Date) created);
                                }
                                return cal.get(Calendar.HOUR_OF_DAY);
                            }, Collectors.counting()));
                    
                    // 转换为前端需要的格式
                    for (Map.Entry<Integer, Long> entry : hourCount.entrySet()) {
                        Map<String, Object> item = new HashMap<>();
                        item.put("name", entry.getKey() + "时");
                        item.put("count", entry.getValue());
                        item.put("percentage", Math.round((entry.getValue() * 100.0 / totalCount) * 100) / 100.0);
                        list.add(item);
                    }
                    break;
                    
                case "user":
                    // 按用户分析
                    Map<String, Long> userCount = logs.stream()
                            .collect(Collectors.groupingBy(SysOperationLog::getUsername, Collectors.counting()));
                    
                    // 转换为前端需要的格式
                    for (Map.Entry<String, Long> entry : userCount.entrySet()) {
                        Map<String, Object> item = new HashMap<>();
                        item.put("name", entry.getKey());
                        item.put("count", entry.getValue());
                        item.put("percentage", Math.round((entry.getValue() * 100.0 / totalCount) * 100) / 100.0);
                        list.add(item);
                    }
                    break;
                    
                default:
                    // 默认按模块分析
                    moduleCount = logs.stream()
                            .collect(Collectors.groupingBy(log -> {
                                String method = log.getMethod();
                                if (method != null && method.contains("/")) {
                                    String[] parts = method.split("/");
                                    if (parts.length > 3) {
                                        return parts[2];
                                    }
                                }
                                return "其他";
                            }, Collectors.counting()));
                    
                    for (Map.Entry<String, Long> entry : moduleCount.entrySet()) {
                        Map<String, Object> item = new HashMap<>();
                        item.put("name", entry.getKey());
                        item.put("count", entry.getValue());
                        item.put("percentage", Math.round((entry.getValue() * 100.0 / totalCount) * 100) / 100.0);
                        list.add(item);
                    }
                    break;
            }
            
            // 计算总体统计信息
            double totalAvgResponseTime = logs.stream()
                    .mapToLong(SysOperationLog::getTime)
                    .average()
                    .orElse(0);
            double totalSuccessRate = logs.stream()
                    .filter(log -> log.getStatus() == 1)
                    .count() * 1.0 / totalCount;
            
            result.put("avgResponseTime", Math.round(totalAvgResponseTime * 100) / 100.0);
            result.put("successRate", Math.round(totalSuccessRate * 10000) / 10000.0);
        }
        
        // 按count降序排序
        list.sort((a, b) -> ((Long) b.get("count")).compareTo((Long) a.get("count")));
        
        result.put("list", list);
        result.put("totalCount", totalCount);
        
        return result;
    }
}